package com.pine.manager.pineframework.trigger.impl;

import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysConfigSaveOrUpdateRequest;
import com.pine.common.redis.cache.RedisCache;
import com.pine.common.trigger.AbstractTriggerTemplate;
import com.pine.common.trigger.TriggerContext;
import com.pine.common.util.user.UserInfo;
import com.pine.common.util.user.UserUtil;
import com.pine.dao.pineframework.entity.SysConfig;
import com.pine.manager.core.CacheNameConstant;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.SysConfigManager;
import com.pine.manager.pineframework.bo.SysConfigBo;
import com.pine.manager.pineframework.convertors.SysConfigConvertor;
import com.pine.manager.pineframework.query.SysConfigQuery;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 系统配置表新增或修改数据 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-13
 */
@Component
@Slf4j
public class SysConfigSaveOrUpdateTrigger extends AbstractTriggerTemplate<SysConfigSaveOrUpdateRequest, Boolean> {

    @Resource
    private SysConfigManager sysConfigManager;

    @Resource
    private SysConfigConvertor sysConfigConvertor;

    @Resource
    private RedisCache redisCache;

    private boolean isSave;

    private SysConfigBo oldSysConfigBo;

    public SysConfigSaveOrUpdateTrigger() {
        super(TriggerTypeEnum.SYS_CONFIG_SAVE_OR_UPDATE);
    }

    @Override
    protected void before(TriggerContext<SysConfigSaveOrUpdateRequest> triggerContext) {
        // 获取请求参数
        SysConfigSaveOrUpdateRequest request = triggerContext.getTriggerRequest();
        isSave = Objects.isNull(request.getId());

        // 尝试查询旧配置
        SysConfigQuery query = new SysConfigQuery();
        query.setId(request.getId());
        query.setConfigKey(request.getConfigKey());
        oldSysConfigBo = sysConfigManager.getOne(query);

        // 校验
        if (isSave) {
            checkOnSave();
        } else {
            checkOnUpdate();
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean trigger(TriggerContext<SysConfigSaveOrUpdateRequest> triggerContext) {
        // 获取请求参数
        SysConfigSaveOrUpdateRequest request = triggerContext.getTriggerRequest();

        // 转换为业务对象，并设置额外字段
        SysConfigBo newSysConfigBo = sysConfigConvertor.saveRequestToEntityBo(request);
        setUserInfo(newSysConfigBo);

        // 转换为实体
        SysConfig sysConfig = sysConfigConvertor.entityBoToEntity(newSysConfigBo);

        // 新增
        if (isSave) {
            if (sysConfigManager.save(sysConfig)) {
                redisCache.set(CacheNameConstant.SYS_CONFIG_CACHE_NAME, sysConfig.getConfigKey(), newSysConfigBo);
                return true;
            }
            return false;
        }

        // 修改
        if (sysConfigManager.updateById(sysConfig)) {
            redisCache.set(CacheNameConstant.SYS_CONFIG_CACHE_NAME, sysConfig.getConfigKey(), newSysConfigBo);
            return true;
        }
        return false;
    }

    private void checkOnSave() {
        // 校验配置key是否重复
        if (Objects.nonNull(oldSysConfigBo)) {
            throw new BusinessException(ExceptionCodeEnum.CONFIG_KEY_EXIST);
        }
    }

    private void checkOnUpdate() {
        // 校验配置key是否存在
        if (Objects.isNull(oldSysConfigBo)) {
            throw new BusinessException(ExceptionCodeEnum.CONFIG_KEY_NOT_EXIST);
        }
    }

    private void setUserInfo(SysConfigBo sysConfigBo) {
        UserInfo userInfo = UserUtil.get();
        if (Objects.nonNull(userInfo)) {
            if (isSave) {
                sysConfigBo.setCreateUserId(userInfo.id());
            }
            sysConfigBo.setUpdateUserId(userInfo.id());
        }
    }
}
